package com.voicechat.firstmet.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PictureViewerActivity;
import com.voicechat.firstmet.activity.PostDetailsActivity;
import com.voicechat.firstmet.base.BaseAdapter;
import com.voicechat.firstmet.bean.CommentBean;
import com.voicechat.firstmet.bean.GifBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.adapter
 * @ClassName: PostDetailsAdapter
 * @Description: java类作用描述
 * @Author: ljp
 * @CreateDate: 2018/9/12 20:24
 * @Version: 1.0
 */
public class PostDetailsAdapter extends BaseAdapter<CommentBean.PageBean.ListBean> {
    @BindView(R.id.image_gif)
    ImageView imageGif;
    @BindView(R.id.tv_gif_number)
    TextView tvGifNumber;
    private Context context;
    private List<CommentBean.PageBean.ListBean> commentBeans;
    private PostBean.PageBean.ListBean listBean;
    private boolean isMe;
    private List<GifBean.PageBean.ListBean> gifBeans;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Bundle data = msg.getData();
                byte[] bitmap = data.getByteArray("bitmap");
                //String tag = data.getString("tag");
                CircleImageView view = (CircleImageView) msg.obj;
                GlideLoadUtils.getInstance().glideLoad(App.getContext(), bitmap, view);
                /*GlideApp.with(context)
                        .load(bitmap)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(view);*/
            }
        }
    };
    private String TAG = "PostDetailsAdapter";
    private ItemClick itemClick;

    public void setItemClick(ItemClick itemClick) {
        this.itemClick = itemClick;
    }

    /**
     * @param context activity_imessage
     * @param tlist   集合
     * @param mLayout 主布局
     */
    public PostDetailsAdapter(Context context, List<CommentBean.PageBean.ListBean> tlist, int mLayout, PostBean.PageBean.ListBean listBean, boolean isMe) {
        super(context, tlist, mLayout);
        this.context = context;
        this.commentBeans = tlist;
        this.listBean = listBean;
        this.isMe = isMe;
    }

    public void setGifBeans(List<GifBean.PageBean.ListBean> gifBeans) {
        this.gifBeans = gifBeans;
    }

    @Override
    protected RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new HeadViewHolder(view);
    }

    @Override
    protected RecyclerView.ViewHolder getItemViewHolder(View view) {
        return new ItemViewHolder(view);
    }

    @Override
    protected RecyclerView.ViewHolder getFooterViewHolder(View view) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof HeadViewHolder) {
            String[] strings = new String[9];
            HeadViewHolder headViewHolder = (HeadViewHolder) viewHolder;
           // setImage(listBean.getAvatarUrl(), headViewHolder.circleIcon);
            if (!listBean.getAvatarUrl().equals(headViewHolder.circleIcon.getTag(R.id.circle_icon))) {
                // 加载图片
                headViewHolder.circleIcon.setTag(R.id.circle_icon, listBean.getAvatarUrl());
                GlideLoadUtils.getInstance().glideLoad(context,OssConfig.OSS_HTTP+listBean.getAvatarUrl(),
                        headViewHolder.circleIcon);
            }
            headViewHolder.tvNikeName.setText(listBean.getNickName());
            headViewHolder.tvPostTitle.setText(listBean.getMdTitle());
            headViewHolder.tvPostContent.setText(listBean.getContent());
            if(!TextUtils.isEmpty(listBean.getVoiceUrl())){
                headViewHolder.linearSendVoice.setVisibility(View.VISIBLE);
                headViewHolder.tvVoiceTime.setText(listBean.getDuration()+"s");
            }
            if (!TextUtils.isEmpty(listBean.getMdUpdateDate())) {
                String standardDate = Utils.getStandardDate(listBean.getMdUpdateDate());//将返回时间转换为多久前
                headViewHolder.tvDate.setText(standardDate);
            }
            if (!TextUtils.isEmpty(listBean.getuType()) && listBean.getuType().equals("2")) {//判断是否是主播
                headViewHolder.imageAnchor.setVisibility(View.VISIBLE);
            } else {
                headViewHolder.imageAnchor.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(listBean.getvType()) &&
                    listBean.getvType().equals("1")) {//判断是vip等级 1 月 2 年 0 不是会员
                headViewHolder.imageVip.setVisibility(View.VISIBLE);
                headViewHolder.imageVip.setImageResource(R.mipmap.vip_month);
            } else if (listBean.getvType().equals("2")) {
                headViewHolder.imageVip.setVisibility(View.VISIBLE);
                headViewHolder.imageVip.setImageResource(R.mipmap.vip_year);
            } else {
                headViewHolder.imageVip.setVisibility(View.GONE);
            }
            if (listBean.getGender() == 1) {//判断性别  1男 2女
                headViewHolder.imageSex.setImageResource(R.mipmap.boy);
                headViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
            } else if (listBean.getGender() == 2) {
                headViewHolder.imageSex.setImageResource(R.mipmap.girl);
                headViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_red);
            }
            Log.i(TAG, "onBindViewHolder: -----" + isMe);
            if (isMe) {
                headViewHolder.linearFans.setVisibility(View.GONE);
               // headViewHolder.tvPostPlayTour.setVisibility(View.GONE);
                headViewHolder.tvText.setVisibility(View.GONE);
            } else {
                if (!TextUtils.isEmpty(listBean.getIsFollow()) && listBean.getIsFollow().equals("0")) {// 关注状态  1未关注 0关注
                    headViewHolder.tvFans.setText("已关注");
                } else {
                    headViewHolder.tvFans.setText("关注");
                }
            }
            if (listBean.getUserId().equals(PostDetailsActivity.mySeleInfo.getId())) {
                headViewHolder.linearFans.setVisibility(View.GONE);
            } else {
                if (listBean.getIsFollow().equals("0")) {// 关注状态  1关注 0未关注
                    headViewHolder.tvFans.setText("关注");
                    headViewHolder.linearFans.setBackgroundResource(R.drawable.login_btn);
                } else if (listBean.getIsFollow().equals("1")) {
                    headViewHolder.tvFans.setText("已关注");
                    headViewHolder.linearFans.setBackgroundResource(R.drawable.login_btn_2);
                }
            }
            if (!TextUtils.isEmpty(listBean.getBirthday())) {
                String substring = listBean.getBirthday().substring(0, 4);
                String time = Utils.getStringTime(new Date());
                int age = (Integer.parseInt(time)) - (Integer.parseInt(substring));
                headViewHolder.tvAge.setText(age + "");
            }
            headViewHolder.linearFans.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setFansClick(v, listBean);
                }
            });
            //照片
            if (TextUtils.isEmpty(listBean.getUrl())) {
                headViewHolder.recyclerPostPicture.setVisibility(View.GONE);
            } else {
                headViewHolder.recyclerPostPicture.setVisibility(View.VISIBLE);
                strings = Utils.spitPictureUrl(listBean.getUrl());
            }
            List<String> listImages = Arrays.asList(strings);
            PostPictureAdapter pictureAdapter = new PostPictureAdapter(context, listImages, R.layout.item_post_picture);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
            headViewHolder.recyclerPostPicture.setHasFixedSize(true);
            headViewHolder.recyclerPostPicture.setLayoutManager(gridLayoutManager);
            headViewHolder.recyclerPostPicture.setAdapter(pictureAdapter);
            //礼物信息
            GifAdapter gifAdapter = new GifAdapter(context, gifBeans, R.layout.item_gif);
            headViewHolder.recyGif.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
            headViewHolder.recyGif.setAdapter(gifAdapter);
            pictureAdapter.setOnClick(new PostPictureAdapter.OnClick() {
                @Override
                public void onSetPictureClick(View view, int position) {
                    //Log.i("onSetPictureClick", "onSetPictureClick: ------"+tlist);
                    ArrayList<String> stringArrayList = new ArrayList<>(listImages);
                    Intent intent = new Intent(context, PictureViewerActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("tlist", (ArrayList<String>) stringArrayList);
                    intent.putExtra("position", position);
                    intent.putExtra("list", bundle);
                    context.startActivity(intent);
                }
            });
            //查看礼物
            headViewHolder.linearMyGif.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setGifClick(v,listBean.getId());
                }
            });
            //打赏
            headViewHolder.tvPostPlayTour.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setReward(v);

                }
            });
            headViewHolder.linearSendVoice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setPlayVoiceClick(listBean,headViewHolder.imageSendVoiceIcon);
                }
            });
            headViewHolder.circleIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setIcon(listBean);

                }
            });
        } else if (viewHolder instanceof ItemViewHolder) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder;
            if (position == 0) {
                return;
            }
            position = position - 1;
            if (position == tlist.size() - 1) {
                itemViewHolder.viewLine.setVisibility(View.GONE);
            }
            CommentBean.PageBean.ListBean commentBean = tlist.get(position);
            Log.i(TAG, "onBindViewHolder: ----------"+commentBean.toString());
            if (!TextUtils.isEmpty(commentBean.getBirthday())) {
                String substring = commentBean.getBirthday().substring(0, 4);
                String time = Utils.getStringTime(new Date());
                int age = (Integer.parseInt(time)) - (Integer.parseInt(substring));
                itemViewHolder.tvAge.setText(age + "");
            }
            if (!TextUtils.isEmpty(commentBean.getvType()) &&
                    commentBean.getvType().equals("1")) {//判断是vip等级 1 月 2 年 0 不是会员
                itemViewHolder.imageVip.setVisibility(View.VISIBLE);
                itemViewHolder.imageVip.setImageResource(R.mipmap.vip_month);
            } else if (commentBean.getvType().equals("2")) {
                itemViewHolder.imageVip.setVisibility(View.VISIBLE);
                itemViewHolder.imageVip.setImageResource(R.mipmap.vip_year);
            } else {
                itemViewHolder.imageVip.setVisibility(View.GONE);
            }
            if (commentBean.getGender() == 1) {//判断性别  1男 2女
                itemViewHolder.imageSex.setImageResource(R.mipmap.boy);
                itemViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
            } else if (commentBean.getGender() == 2) {
                itemViewHolder.imageSex.setImageResource(R.mipmap.girl);
                itemViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_red);
            }
            if (!TextUtils.isEmpty(commentBean.getIsFabulous())) {
                if (commentBean.getIsFabulous().equals("0")) {//我是否点赞  1 已经点赞   0 未点赞
                    itemViewHolder.imageLikes.setImageResource(R.mipmap.unlike);
                } else {
                    itemViewHolder.imageLikes.setImageResource(R.mipmap.like);
                }
            }
            if ( commentBean.getuType()== 2) {//判断是否是主播
                itemViewHolder.imageAnchor.setVisibility(View.VISIBLE);
            } else {
                itemViewHolder.imageAnchor.setVisibility(View.GONE);
            }
            itemViewHolder.tvLikeNumber.setText(commentBean.getFabulousCount() + "");
            itemViewHolder.tvConent.setText(commentBean.getContent());
            if (!TextUtils.isEmpty(commentBean.getCreateDate())) {
                String standardDate = Utils.getStandardDate(commentBean.getCreateDate());//将返回时间转换为多久前
                itemViewHolder.tvDate.setText(standardDate);
            }
            //setImage(commentBean.getAvatarUrl(), itemViewHolder.circleIcon);
            if(!TextUtils.isEmpty(commentBean.getAvatarUrl())) {
                if (!commentBean.getAvatarUrl().equals(itemViewHolder.circleIcon.getTag(R.id.circle_icon))) {
                    // 加载图片
                    itemViewHolder.circleIcon.setTag(R.id.circle_icon, commentBean.getAvatarUrl());
                    GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + commentBean.getAvatarUrl(),
                            itemViewHolder.circleIcon);
                }
            }
            itemViewHolder.tvNikeName.setText(commentBean.getNickName());
            itemViewHolder.linearLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setLikeClick(itemViewHolder.imageLikes, commentBean, itemViewHolder.tvLikeNumber);
                }
            });
            //itemViewHolder.tvLikeNumber.setText(listBean.getFabulousCount());
            if (commentBean.getDiscussCount() != 0) {
                itemViewHolder.linearComment.setVisibility(View.VISIBLE);
                itemViewHolder.tvCommend.setText("查看全部" + commentBean.getDiscussCount() + "条评论");
                itemViewHolder.linearComment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemClick.setLinearComment(commentBean);
                    }
                });
            } else {
                itemViewHolder.linearComment.setVisibility(View.GONE);
            }
            itemViewHolder.linearCommentClick.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setCommentClick(v, commentBean);
                }
            });
            itemViewHolder.circleIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick.setIcon(commentBean);
                }
            });
        }
    }
    private void setImage(String url, View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).fileDownload(url, new OssClient.OnDownloadFile() {
                    @Override
                    public void onDownFileSuccess(InputStream inputStream) {
                        byte[] bitmap = null;
                        try {
                            bitmap = OssConfig.readInputStreamToByte(inputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //if(view.getTag() != null && view.getTag().equals(url)) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.obj = view;
                        Bundle bundle = new Bundle();
                        //bundle.putString("tag",url);
                        bundle.putByteArray("bitmap", bitmap);
                        message.setData(bundle);
                        handler.sendMessage(message);
                        //  }
                    }

                    @Override
                    public void onDownFileProgress(String progress) {
                    }
                });
            }
        }).start();

    }

    class HeadViewHolder extends BaseViewHolder {
        @BindView(R.id.circle_icon)
        CircleImageView circleIcon;
        @BindView(R.id.tv_nike_name)
        TextView tvNikeName;
        @BindView(R.id.image_sex)
        ImageView imageSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.linear_sex_age)
        LinearLayout linearSexAge;
        @BindView(R.id.image_vip)
        ImageView imageVip;
        @BindView(R.id.tv_date)
        TextView tvDate;
        @BindView(R.id.tv_post_title)
        TextView tvPostTitle;
        @BindView(R.id.tv_post_content)
        TextView tvPostContent;
        @BindView(R.id.recycler_post_picture)
        RecyclerView recyclerPostPicture;
        @BindView(R.id.tv_post_play_tour)
        TextView tvPostPlayTour;
        @BindView(R.id.linear_my_gif)
        LinearLayout linearMyGif;
        @BindView(R.id.recy_gif)
        RecyclerView recyGif;
        @BindView(R.id.image_isanchor)
        ImageView imageAnchor;
        @BindView(R.id.tv_fans)
        TextView tvFans;
        @BindView(R.id.tv_text)
        TextView tvText;
        @BindView(R.id.linear_fans)
        LinearLayout linearFans;
        @BindView(R.id.image_send_voice_icon)
        ImageView imageSendVoiceIcon;
        @BindView(R.id.tv_voice_time)
        TextView tvVoiceTime;
        @BindView(R.id.linear_send_voice)
        RelativeLayout linearSendVoice;

        public HeadViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemViewHolder extends BaseViewHolder {
        @BindView(R.id.circle_icon)
        CircleImageView circleIcon;
        @BindView(R.id.tv_nike_name)
        TextView tvNikeName;
        @BindView(R.id.image_sex)
        ImageView imageSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.linear_sex_age)
        LinearLayout linearSexAge;
        @BindView(R.id.image_vip)
        ImageView imageVip;
        @BindView(R.id.tv_like_num)
        TextView tvLikeNumber;
        @BindView(R.id.tv_date)
        TextView tvDate;
        @BindView(R.id.linear_comment)
        LinearLayout linearComment;
        @BindView(R.id.view_line)
        View viewLine;
        @BindView(R.id.tv_commend)
        TextView tvCommend;
        @BindView(R.id.image_likes)
        ImageView imageLikes;
        @BindView(R.id.tv_conent)
        TextView tvConent;
        @BindView(R.id.linear_like)
        LinearLayout linearLike;
        @BindView(R.id.linear_comment_click)
        LinearLayout linearCommentClick;

         @BindView(R.id.image_isanchor)
         ImageView imageAnchor;
        public ItemViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface ItemClick {
        void setLinearComment(CommentBean.PageBean.ListBean listBean);

        void setLikeClick(ImageView view, CommentBean.PageBean.ListBean listBean, TextView view2);

        void setCommentClick(View view, CommentBean.PageBean.ListBean listBean);

        void setFansClick(View view, PostBean.PageBean.ListBean listBean);

        void setGifClick(View view, String postId);

        void setReward(View view);

        void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, ImageView view);

        void setIcon(PostBean.PageBean.ListBean listBean);
        void setIcon(CommentBean.PageBean.ListBean commentBean);
    }
}
